<?php

if (!defined('DIR_SEP')) {
    define('DIR_SEP', DIRECTORY_SEPARATOR);
}
if (!defined('MODULES_DIR')) {
    define('MODULES_DIR', dirname(__FILE__).DIR_SEP."..".DIR_SEP);
}
require_once(MODULES_DIR.'db.inc');
require_once(MODULES_DIR.'config.inc');
require_once(MODULES_DIR.'tag.inc');

class BlogTitle
{
	public $title;
	public $creationDate;
	public $permalink;
	public $id;
	public $children;
	
	public function getUrl()
	{
		return BlogPost::getUrlStatic($this->creationDate,$this->permalink,$this->id);
	}	
}

class BlogPost
{
	protected $db;
	public $id;
	public $creationDate;
	public $title;
	public $desc;
	public $content;
	public $viewCount;
	public $permalink;
	public $commentCount;
	public $deleted;
	public $tags;

	function __construct()
	{
		$this->db = DB::getInstance()->getDB();
	}
	
	function add($title,$desc,$content,$tags)
	{
		try
		{
			$content = str_replace("'","\'",$content);

			$permalink = Util::cutStringFullWords($title,100);
			$permalink = preg_replace("[\W]","_",$permalink);
			$permalink .= "_";
			while(strpos($permalink,"__",0)!= false) 
				$permalink = str_replace("__","_",$permalink);

			//open transaction
			$query = mysql_query('BEGIN',$this->db);

			if (!$query)
				throw new Exception(mysql_error());

			//add blog post item
			$sql ="insert into t_blog_post (title,content,description,view_count,permalink,deleted)
				values ('".$title."','".$content."','".$desc."',0,'".$permalink."',0)";

			$query = mysql_query($sql,$this->db);

			if (!$query)
				throw new Exception(mysql_error());
			
			$postId = mysql_insert_id();
			
			$tag = new Tag();
			//foreach tag add relation to tag
			for($i = 0;$i<count($tags);$i++)
			{
				$tagId = $tag->add($tags[$i]);
				$sql = "insert into t_blog_post_tag (post_id,tag_id) values (".$postId.",".$tagId.")";

				$query = mysql_query($sql,$this->db);

				if (!$query)
					throw new Exception(mysql_error());				
			}
			
			//commiting
			$query = mysql_query('COMMIT',$this->db);

			if (!$query)
				throw new Exception(mysql_error());
				
			return true;
		}
		catch(Exception $ex)
		{
			mysql_query('ROLLBACK',$this->db);
			return false;
		}		
	}

	function update($title,$desc,$content,$tags)
	{
		try
		{
			//open transaction
			$query = mysql_query('BEGIN',$this->db);

			if (!$query)
				throw new Exception(mysql_error());

			//updating the post
			$content = str_replace("'","\'",$content);
				
			$sql ="update t_blog_post set title = '".$title."',
					content = '".$content."',
					description = '".$desc."'
					where id = ".$this->id;

			$query = mysql_query($sql,$this->db);
			
			if (!$query)
				throw new Exception(mysql_error());

			//updating the related tags
			$sql = "delete from t_blog_post_tag where post_id = ".$this->id;
			$query = mysql_query($sql,$this->db);
			if (!$query)
				throw new Exception(mysql_error());
			
			$tag = new Tag();
			//foreach tag add relation to tag
			for($i = 0;$i<count($tags);$i++)
			{
				$tagId = $tag->add($tags[$i]);
								
				$sql = "insert into t_blog_post_tag (post_id,tag_id) values (".$this->id.",".$tagId.")";

				$query = mysql_query($sql,$this->db);

				if (!$query)
					throw new Exception(mysql_error());				
			}
			
			//commiting
			$query = mysql_query('COMMIT',$this->db);

			if (!$query)
				throw new Exception(mysql_error());
				
			return true;
		}
		catch(Exception $ex)
		{
			mysql_query('ROLLBACK',$this->db);
			return false;
		}		
	}
	
	/*
	 * Promotes the view count of the feed item for statistics.
	 */
	function promoteViewCount()
	{
		try
		{
			$sql = "update t_blog_post set view_count = view_count + 1 where id = ".$this->id;
	
			//As the object is being cached, it loses it's connectivity to the DB, so don't use the member _db object.
			$query = mysql_query($sql,DB::getInstance()->getDB());
	
			if (!$query)
				throw new Exception(mysql_error());
		
			return true;
		}
		catch(Exception $ex)
		{
			return false;
		}		
	}
	
	public function load($itemId)
	{
		try
		{
			$sql ="select tbp.id,tbp.title,tbp.description,tbp.content,tbp.creation_date,tbp.view_count,tbp.permalink,
					CASE deleted WHEN false THEN 0 WHEN true THEN 1 END as deleted,
					(select count(1) from t_blog_post_comment tbpc where tbpc.post_id = tbp.id ) as comment_count
					FROM t_blog_post tbp
					WHERE id = ".$itemId;

			$query = mysql_query($sql,$this->db);

			if (!$query)
				throw new Exception(mysql_error());
	
			if(mysql_num_rows($query)==0)
				throw new Exception("no such post");
				
			$row = mysql_fetch_row($query);
							
			$this->id = $itemId;
			$this->title = $row[1];
			$this->desc = $row[2];
			$this->content = $row[3];
			$this->creationDate = strtotime($row[4]);
			$this->viewCount = $row[5];
			$this->permalink = $row[6];
			$this->deleted = $row[7] == "1" ? true : false;
			$this->commentCount = $row[8];
			
			$rows = Tag::getByBlogPost($itemId);
			
			$this->tags = Array();
			
			foreach($rows as $row)
			{
				$tag = new Tag();
				$tag->id = $row["id"];
				$tag->tag = $row["tag"];
				$this->tags[] = $tag;
			}	
			
			return true;
		}
		catch(Exception $ex)
		{
			return false;
		}	
	}

	public function delete()
	{
		try
		{
			if(!$this->db)
				$this->db = DB::getInstance()->getDB();
			
			$sql = 	"update t_blog_post set deleted = 1
					where id = ".$this->id;
							
			$query = mysql_query($sql,$this->db);

			if (!$query)
				throw new Exception(mysql_error());

				return true;
		}
		catch(Exception $ex)
		{
			return false;
		}	
	}
	
	public function getUrl()
	{
		return BlogPost::getUrlStatic($this->creationDate,$this->permalink,$this->id);
	}
	
	public static function getUrlStatic($creationDate,$permalink,$id)
	{
		global $G_HOME;
		
		$config = Config::getInstance();
		$usePermalinks = $config->get('/site/features/permalinks/@enabled');
		
		$link = '';
		
		if($usePermalinks == '1' && strlen($permalink) > 0)
			$link = strtolower(Util::combinePath($G_HOME,"blog/".date("Y",$creationDate)."/".date("m",$creationDate)."/".$permalink.$id));
		else
			$link = Util::combinePath($G_HOME,"index.php?pg=view_post&amp;postId=".$id);
			
		return $link;
	}
	
	static function getTagPosts($tagId,$orderBy,$startRow,$count)
	{
		try
		{
			$orderBy = trim($orderBy);
			
			if( strlen($orderBy) > 0 )
				$orderBy = ' order by '.$orderBy.' ';
				
			$count = ( $count <= 0) ? DB::$ALL_ROWS : $count;

			$sql ="select tbp.id,tbp.creation_date,tbp.title,tbp.content,tbp.view_count,tbp.permalink,
					(select count(1) from t_blog_post_comment tbpc where tbpc.post_id = tbp.id) as comment_count
					FROM t_blog_post_tag tbpt 
					inner join t_blog_post tbp on tbp.id = tbpt.post_id 
					where tbp.deleted = false and tbpt.tag_id = ".$tagId.
					" ".$orderBy." limit ".$startRow.",".$count;

			$query = mysql_query($sql,DB::getInstance()->getDB());

			if (!$query)
				throw new Exception(mysql_error());
			
			$result = array();
			
			while( list($id,$creationDate,$title,$content,$viewCount,$permalink,$commentCount) = mysql_fetch_row($query))
			{
				$blogPost = new BlogPost();
				
				$blogPost->id = $id;
				$blogPost->feedId = $feed_id;
				$blogPost->creationDate = strtotime($creationDate);
				$blogPost->title = $title;
				$blogPost->content = $content;
				$blogPost->link = $link;
				$blogPost->feedName = $feedName;
				$blogPost->viewCount = $viewCount;
				$blogPost->permalink = $permalink;
				$blogPost->commentCount = $commentCount;

				$result[] = $blogPost;
			}

			return $result;
		}
		catch(Exception $ex)
		{
			return null;
		}	
	}

	static function getPosts($orderBy,$startRow,$count)
	{
		try
		{
			$orderBy = trim($orderBy);
			
			if( strlen($orderBy) > 0 )
				$orderBy = ' order by '.$orderBy.' ';
				
			$count = ( $count <= 0) ? DB::$ALL_ROWS : $count;

			$sql ="select tbp.id,tbp.creation_date,tbp.title,tbp.content,tbp.view_count,tbp.permalink,
					(select count(1) from t_blog_post_comment tbpc where tbpc.post_id = tbp.id) as comment_count
					FROM t_blog_post tbp 
					where tbp.deleted = false".
					" ".$orderBy." limit ".$startRow.",".$count;

			$query = mysql_query($sql,DB::getInstance()->getDB());

			if (!$query)
				throw new Exception(mysql_error());
			
			$result = array();
			
			while( list($id,$creationDate,$title,$content,$viewCount,$permalink,$commentCount) = mysql_fetch_row($query))
			{
				$blogPost = new BlogPost();
				
				$blogPost->id = $id;
				$blogPost->feedId = $feed_id;
				$blogPost->creationDate = strtotime($creationDate);
				$blogPost->title = $title;
				$blogPost->content = $content;
				$blogPost->link = $link;
				$blogPost->feedName = $feedName;
				$blogPost->viewCount = $viewCount;
				$blogPost->permalink = $permalink;
				$blogPost->commentCount = $commentCount;

				$result[] = $blogPost;
			}

			return $result;		
		}
		catch(Exception $ex)
		{
			return null;
		}	
	}
	
	static function getTagCount($tagId)
	{
		try
		{
			$sql = "select count(1) as counter 
					from t_blog_post tbp
					inner join t_blog_post_tag tbpt on tbpt.post_id = tbp.id 
					where tbp.id = ".$tagId;
			$query = mysql_query($sql,DB::getInstance()->getDB());
			if (!$query)
				throw new Exception(mysql_error());
			$row = mysql_fetch_assoc($query);
			return $row["counter"];
		}
		catch(Exception $ex)
		{
			return null;
		}	
	}

	
	static function getTitles()
	{
		try
		{
			$sql ="select permalink,id,creation_date,title from t_blog_post where deleted = 0 order by creation_date desc"; 

			$query = mysql_query($sql,DB::getInstance()->getDB());

			if (!$query)
				throw new Exception(mysql_error());
			
			$years = array();
			
			$currMonth = null;
			$currYear = null;
			
			while( list($permalink,$id,$creationDate,$title) = mysql_fetch_row($query))
			{
				$creationDate = strtotime($creationDate);
								
				if(!isset($currYear) || $currYear->title != date("Y",$creationDate))
				{
					$currMonth = null;
					$currYear = new BlogTitle();
					$currYear->title = date("Y",$creationDate);
					$years[] = $currYear;
					$currYear->children = Array();
				}

				if( !isset($currMonth) || $currMonth->title != date("M",$creationDate))
				{
					$currMonth = new BlogTitle();
					$currMonth->title = date("M",$creationDate);
					$currYear->children[] = $currMonth;					
				}

				$blogTitle = new BlogTitle();
				$currMonth->children[] = $blogTitle;
				$blogTitle->title = $title;
				$blogTitle->creationDate = $creationDate;
				$blogTitle->permalink = $permalink;
				$blogTitle->id = $id;
			}

			foreach($years as $year)
			{
				$count =0;
				foreach($year->children as $month)
				{
					$month->title .= " (".count($month->children).")";
					$count += count($month->children);
				}
				$year->title .= " (".$count.")";
			}
			
			return $years;
		}
		catch(Exception $ex)
		{
			return null;
		}
	}
}

?>